public class Solution8 {
    public int myAtoi(String s) {
        long res = 0;
        boolean isNegative = false;
        boolean isConfirm = false;
        for (int i = 0; i < s.length(); i++) {
            if(Integer.MAX_VALUE < res){
                break;
            }
            char tmpC = s.charAt(i);
            if('0' <= tmpC && tmpC <= '9'){
                isConfirm = true;
                res = res * 10 + (tmpC - '0');
            }
            else if((tmpC == '+' || tmpC == '-') && res == 0 && !isConfirm){
                isConfirm = true;
                if(tmpC == '-') {
                    isNegative = true;
                }
            }
            else if(tmpC == ' ' && !isConfirm){
                continue;
            }
            else{
                break;
            }
        }
        res = isNegative ? -res : res;
        if(res < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        if(res > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        return (int) res;
    }

    public static void main(String[] args) {
        Solution8 s = new Solution8();
        System.out.println(s.myAtoi("  -42"));
    }
}
